/**
 * Created by Freeman on 2017/7/11.
 */
const md5 = require('md5')
const UserModel = require('../models/user')
const jwt = require('jsonwebtoken')
class UserController {

  // 用户注册
  static async register (ctx) {
    const {username, nickname, password, apassword, profile} = ctx.request.body
    if (!username || !password) {
      return ctx.error({msg: '用户名或密码不能为空!'})
    }
    if (password !== apassword) {
      return ctx.error({msg: '两次输入的密码不一致!'})
    }
    const ishas = await UserModel.findOne({username})
    if (ishas) {
      return ctx.error({msg: '该用户已存在!'})
    }
    const result = await UserModel.create({username, nickname, password: md5(password), profile})
    if (!result) {
      return ctx.error({msg: '注册失败!'})
    }
    return ctx.success({msg: '注册成功'})
  }

  // 用户登录
  static async login (ctx) {
    const {username, password} = ctx.request.body
    if (!username || !password) {
      return ctx.error({msg: '获取用户失败!'})
    }
    const data = await UserModel.findOne({username, password: md5(password)}, {password: 0})
    if (!data) return ctx.error({msg: '用户名或密码错误!'})
      const result = {
          token:jwt.sign({"_id": data._id,
              "username": data.username,
              "role": data.role,
          }, 'shhhhh'),
          userInfo:data
      }
    ctx.success({msg: '登录成功',data:result})
  }

}

module.exports = UserController
